<template>
  <NCard class="login-card" title="注册">
    <NForm ref="registerRef" :model="registerModel" :rules="registerRules">
      <NFormItem path="username" label="用户名">
        <NInput
          v-model:value="registerModel.username"
          placeholder="请输入用户名"
          @keydown.enter.prevent="submit"
        />
      </NFormItem>
      <NFormItem path="password" label="密码">
        <NInput
          v-model:value="registerModel.password"
          type="password"
          placeholder="请输入密码"
          @keydown.enter.prevent="submit"
        />
      </NFormItem>
      <NFormItem path="repassword" label="确认密码">
        <NInput
          v-model:value="registerModel.repassword"
          type="password"
          placeholder="请再次输入密码"
          @keydown.enter.prevent="submit"
        />
      </NFormItem>
      <div class="login-button">
        <NButton @click="submit" type="primary">注册</NButton>
        <NButton @click="toLogin" type="primary" strong secondary
          >去登录</NButton
        >
      </div>
    </NForm>
  </NCard>
</template>

<script lang="ts" setup>
import { NCard, NForm, NFormItem, NInput, NButton, useMessage } from "naive-ui";
import { useRouter } from "vue-router";

import { useRegister } from "../hooks/Register";

const router = useRouter();
const message = useMessage();

const { registerRef, registerModel, toRegister, registerRules } = useRegister();

function toLogin() {
  router.push("/login");
}

function submit() {
  registerRef.value?.validate(async (err) => {
    if (!err) {
      try {
        const msg = await toRegister();
        router.push("/");
        message.success(msg);
      } catch (e: any) {
        message.error(e.response.data.msg);
      }
    } else {
      message.error("请检查输入的内容");
    }
  });
}
</script>

<style lang="less" scoped>
.login-card {
  max-width: 500px;
  margin: 3em auto;
  padding: 2em 1em;

  .login-button {
    margin: 1em 0;
    display: flex;
    justify-content: space-around;

    button {
      padding: 0.5em 3em;
    }
  }
}
</style>
